# -- coding: utf-8 -- 
# Name: views
from flask import Blueprint,render_template,request,session,redirect,url_for
from .models import Users
from .forms import LoginForm
from flask import make_response
from utils.captcha import create_validate_code
from datetime import timedelta
from flask import g
import config


bp=Blueprint("admin", __name__,url_prefix='/admin')


@bp.route("/login/",methods=['GET','POST'])
def login():
    error = None
    if request.method == 'GET':
        return render_template('admin/login.html')
    else:
        user = request.form.get('username')
        pwd = request.form.get('password')
        users = Users.query.filter_by(username=user).first()
        if users:
            if user == users.username and users.check_password(pwd):
                session['user_id'] = users.uid
                print('pwd is yes')
                return redirect(url_for('admin.index'))
            else:
                error = 'username or password id failed'
                return render_template('admin/login.html', message=error)
        return render_template('admin/login.html', message='no try,bye bye')

    form = LoginForm(request.form)
    if form.validate():
        user = request.form.get('userame')
        pwd = request.form.get('password')
        captcha = request.form.get('captcha')
        if session.get('image').lower() != captcha.lower():
            return render_template('admin/login.html', message="验证码错误")
        users = Users.query.filter_by(username=user).first()
        if Users:
            if user == users.username and users.check_password(pwd):
                session['user_id'] = users.uid
                print('password is true')
            else:
                error = 'username or password is failed'
                return render_template('amdin/login.html', message=error)
        else:
            return render_template('admin/login.html', message='sorry no this user')
    else:
        return render_template('admin/login.html', message=form.errors)


@bp.route('/')
def index():
    return render_template('admin/login.html')

@bp.route('/code/')
def get_code():
    code_img,strs = create_validate_code()
    buf = BytesIO()
    code_img.save(buf,'JPEG',quality=70)
    buf_str = buf.getvalue()
    response = make_response(buf_str)
    response.headers['Content-Type'] = 'image/jpeg'
    session['image'] = strs
    return response

online = request.form.get('online')
if online:
    session.permanent = True
    bp.permanent_session_lifetime = timedelta(days=14)

@bp.before_request
def before_request():
    if user_id in session:
        user_id = session.get(user_id)
        user = Users.query.get(user_id)
        if user:
            g.admin_user = user